<template>
  <div>
       <van-nav-bar
          title="小智同学"
          left-text="返回"
          left-arrow
          @click-left="$router.back()"
          class="nav-bar"
        />
        <!-- 消息列表 -->
        <van-cell-group class="list" ref="list">
            <van-cell :title="item.msg"  v-for="(item,index) in list" :key="index"/>
        </van-cell-group>
        <!-- 发送消息 -->
        <van-cell-group class="send-con">
          <van-field v-model="message" :border="false" placeholder="请输入消息内容" />
          <van-button size="small" type="primary" class="button" @click="onSend">发送</van-button>
        </van-cell-group>
  </div>
</template>

<script>
import io from 'socket.io-client'
import {setItem,getItem} from '@/utils/storage.js'
export default {
  name: 'TlineChat',
  components: {  },
  directives: {  },
  data() {
    return {
       message:'',
       socket:null, //通信对象
       list: getItem('chat-message') || [],//消息列表

    };
  },
  mounted() {
    this.scrollToBottom()
  },
  watch:{
    list(){
      setItem('chat-message',this.list)
      //数据改变，视图不是立即的
      //如果你要在操作数据之后立即操作数据影响的视图DOM,n那么最好把代码放到this.$nextTick函数中
      this.$nextTick(()=>{
         this.scrollToBottom()
      })
    }
  },
  methods: {
     onSend(){
       //请求发送消息
       const data={
          msg:this.message,
         timestamp:Date.now()
       }
       this.socket.emit('message',data)
       this.list.push(data)
       this.message=""
     },
     scrollToBottom(){
       const list= this.$refs['list']
       list.scrollTop=list.scrollHeight
     }
  },
  created(){
    //建立连接 接口有问题~
    const socket=io('http://ttapi.research.itcast.cn/')
    this.socket=socket
    socket.on('connext',()=>{
      console.log('建立连接')
    })
    //监听message事件
    socket.on('message',(data)=>{
      console.log(data)
      this.list.push(data)
    })
    //断开连接
    socket.on('disconnect',()=>{})

    window.socket=socket
  }
};
</script>

<style lang="less" scoped>
.list{
   position: fixed;
   left:0;
   right:0;
   top:46px;
   bottom: 44px;
   overflow-y: auto;
}
.send-con{
   display: flex;
   padding:0 5px;
   align-items: center;
   position:fixed;
   left:0;
   right:0;
   bottom:0;
}
.button{
  width:100px;
}
</style>
